package com.hcb.tonguetiphealth.widget.homepage;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader.ImageCallBack;
import com.hcb.tonguetiphealth.manager.MemberManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.CalendarActivity;
import com.hcb.tonguetiphealth.view.ChatActivity;
import com.hcb.tonguetiphealth.view.CityWideActivity;
import com.hcb.tonguetiphealth.view.DIYActivity;
import com.hcb.tonguetiphealth.view.HeadPortraitActivity;
import com.hcb.tonguetiphealth.view.HealthCateActivity;
import com.hcb.tonguetiphealth.view.HealthMirrorActivity;
import com.hcb.tonguetiphealth.view.HealthShareActivity;
import com.hcb.tonguetiphealth.view.MemberActivity;
import com.hcb.tonguetiphealth.view.MoreActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.view.RecommendHealthActivity;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class HomepagePersonalWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "HomepagePersonalWidget";
	private static final String url_exit = Global.URL + Global.servletLoginOut;
	private Activity ctx;
	
	private WindowManager wm = null;
	private WindowManager.LayoutParams wmParams = null;
	private ImageView bt_more = null;
	// ImageView的alpha值   
	private int mAlpha = 0;
	private boolean isHide;
	private PopupWindow myPopupWindow;
	private LinearLayout ll_jkdr, ll_health2, ll_jkcd, ll_diy, ll_shejianhot, ll_sjjk, ll_share ;
	private View mView;
		
		private ScrollView scrollView;

	private Handler mHandler;
	private TextView tvUserName, tvSex, tvLabels, tvInfo, tv_heigth, tv_weight, tv_checkedBody;
	private RatingBar rbLevel;
	private Button btFans, btAttention, bt_editInfo, bt_watchedRes, bt_ordered, bt_trends, bt_chat, bt_cate, btHealthShare;
	private Button btPlan;
	private User user;
	private ImageView imgUser;
	
	private LinearLayout llback, llexit;
//	private ImageView imgUporDown;
//	private ImageView infoImgUporDown;
	
//	private LinearLayout llLabels, llInfo ;
	
	public HomepagePersonalWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		mView = inflate(context, R.layout.homepage_personnal_info, this); 
		
		scrollView = (ScrollView)findViewById(R.id.homepage_personal_scrollview);
		initFloatView();
		
		//db = DBManager.getInstance(ctx);
		//new BottomWidget(ctx,this);
		bindView();
		bindEvent();
		initData();
		
		if(Global.memberList == null) {
			Global.memberList = new ArrayList<User>();
			Global.memberList = new MemberManager(ctx).getMemberList(Global.memberList);
		}
		//启动聊天服务
		ctx.startService(Global.serviceIntent);
	}

	/**
	 * 初始化悬浮按钮
	 */
	private void initFloatView() {
		// 获取WindowManager
		wm=(WindowManager)ctx.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
		//wm = (WindowManager) ctx.getWindowManager();
		// 设置LayoutParams(全局变量）相关参数
		wmParams = new WindowManager.LayoutParams();

		wmParams.type = WindowManager.LayoutParams.TYPE_PHONE; // 设置window type
		wmParams.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
		// 设置Window flag
		wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
				| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

		// 以屏幕左上角为原点，设置x、y初始值
		wmParams.x = 0;
		wmParams.y = 0;
		// 设置悬浮窗口长宽数据
		wmParams.width = 40;
		wmParams.height = 80;

		// 创建悬浮按钮
		createFloatView();
		// createLeftFloatView();
		// createRightFloatView();
		
		setPopupWindow();
	}

	/**
	 * 创建悬浮按钮
	 */
	private void createFloatView() {
		bt_more = new ImageView(ctx);
		bt_more.setImageResource(R.drawable.prev);
		bt_more.setScaleType(ScaleType.FIT_XY);
		bt_more.setAlpha(0);
		bt_more.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				bt_more.setVisibility(Button.GONE);
				if(!myPopupWindow.isShowing()) {
					try {
						myPopupWindow.showAtLocation(mView, Gravity.RIGHT| Gravity.CENTER_VERTICAL, 0, 0);
					} catch(Exception e) {
						Log.e(TAG, "showAtLocation", e);
					}
				}
			}
		});
		// 调整悬浮窗口
		wmParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
		// 显示myFloatView图像
		wm.addView(bt_more, wmParams);
	}
	/**展示window*/
	private void setPopupWindow(){
		LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.personal_hide_operate, null); 
       // ll_jkdr, ll_health2, ll_jkcd, ll_diy, ll_shejianhot, ll_sjjk, ll_share
        
        ll_jkdr = (LinearLayout)view.findViewById(R.id.personal_hide_jkdr_linearlayout);
        ll_health2 = (LinearLayout)view.findViewById(R.id.personal_hide_health2_linearlayout);
        ll_jkcd = (LinearLayout)view.findViewById(R.id.personal_hide_jkcd_linearlayout);
        ll_diy = (LinearLayout)view.findViewById(R.id.personal_hide_diy_linearlayout);
        ll_shejianhot = (LinearLayout)view.findViewById(R.id.personal_hide_shejianhot_linearlayout);
        ll_sjjk = (LinearLayout)view.findViewById(R.id.personal_hide_sjjk_linearlayout);
        ll_share = (LinearLayout)view.findViewById(R.id.personal_hide_share_linearlayout);
        ll_jkdr.setOnClickListener(this);
        ll_health2.setOnClickListener(this);
        ll_jkcd.setOnClickListener(this);
        ll_diy.setOnClickListener(this);
        ll_shejianhot.setOnClickListener(this);
        ll_sjjk.setOnClickListener(this);
        ll_share.setOnClickListener(this);
		//myPopupWindow= new PopupWindow(gridView, LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT, true);
		myPopupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, true);
		myPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		myPopupWindow.setAnimationStyle(R.style.PopupAnimation_personal_hide);
	 // myPopupWindow.showAtLocation(findViewById(R.id.rlayout), Gravity.LEFT| Gravity.LEFT, 0, 0);
		myPopupWindow.update();//更新当前状态，比如展开或者关闭等等
	}

	/**
	 * 图片渐变显示处理
	 */
	private Handler btHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1 && mAlpha < 255) {
				// System.out.println("---"+mAlpha);
				mAlpha += 50;
				if (mAlpha > 255)
					mAlpha = 255;
				bt_more.setAlpha(mAlpha);
				bt_more.invalidate();
				if (!isHide && mAlpha < 255)
					btHandler.sendEmptyMessageDelayed(1, 100);
			} else if (msg.what == 0 && mAlpha > 0) {
				// System.out.println("---"+mAlpha);
				mAlpha -= 10;
				if (mAlpha < 0)
					mAlpha = 0;
				bt_more.setAlpha(mAlpha);
				bt_more.invalidate();
				if (isHide && mAlpha > 0)
					btHandler.sendEmptyMessageDelayed(0, 100);
			}
		}
	};

	private void showFloatView() {
		isHide = false;
		btHandler.sendEmptyMessage(1);
	}

	private void hideFloatView() {
		new Thread() {
			public void run() {
				try {
					Thread.sleep(1500);
					isHide = true;
					btHandler.sendEmptyMessage(0);
				} catch (Exception e) {
					;
				}
			}
		}.start();
	}
	
	private void bindView(){
		tvUserName = (TextView)findViewById(R.id.homepage_personal_textview);
		tvSex = (TextView)findViewById(R.id.homepage_personal_sex_textview);
		tv_checkedBody =(TextView)findViewById(R.id.homepage_personal_food_health_check_textview);
		tv_heigth =(TextView)findViewById(R.id.homepage_personal_food_health_height_textview);
		tv_weight =(TextView)findViewById(R.id.homepage_personal_food_health_weight_textview);
		tvLabels =(TextView)findViewById(R.id.homepage_personal_labes_textview);
		tvInfo = (TextView)findViewById(R.id.homepage_personal_info_textview);
		rbLevel = (RatingBar)findViewById(R.id.homepage_personal_info_ratingbar);
		imgUser = (ImageView)findViewById(R.id.homepage_personal_img);
 
		bt_editInfo = (Button)findViewById(R.id.homepage_personal_edit_info_bt);
		bt_watchedRes = (Button)findViewById(R.id.homepage_personal_attention_res_bt);
		bt_ordered = (Button)findViewById(R.id.homepage_personal_consumption_bt);
		bt_trends = (Button)findViewById(R.id.homepage_personal_share_bt);
		bt_chat = (Button)findViewById(R.id.homepage_personal_new_message_bt);
		btFans = (Button)findViewById(R.id.homepage_personal_fans_bt);
		btAttention = (Button)findViewById(R.id.homepage_personal_attention_bt);
		btPlan = (Button)findViewById(R.id.homepage_personal_plan_bt);
		bt_cate = (Button)findViewById(R.id.homepage_personal_cate_bt);
		btHealthShare = (Button)findViewById(R.id.homepage_personal_comment_bt);
		
		llback = (LinearLayout)findViewById(R.id.res_info_back);
		llexit = (LinearLayout)findViewById(R.id.homepage_personal_info_exit);
		
		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在退出个人后台中心...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					Global.user = null;
					Global.clear();
					ctx.finish();
					break;
				case MotionEvent.ACTION_DOWN:
					showFloatView();
					break;
				case MotionEvent.ACTION_UP:
					hideFloatView();
					break;
					
				}
			}
			
		};
		scrollView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
	    		case MotionEvent.ACTION_MOVE:
				case MotionEvent.ACTION_DOWN:
					if(bt_more.getVisibility() == Button.GONE) {
						bt_more.setVisibility(Button.VISIBLE);
					}
					showFloatView();			
					break;
				case MotionEvent.ACTION_UP:
					hideFloatView();				
					break;
			}
				return false;
			}
		});
		
//		llLabels = (LinearLayout)findViewById(R.id.homepage_member_labels_linearlayout);
//		llInfo = (LinearLayout)findViewById(R.id.homepage_member_info_linearlayout);
		
//		imgUporDown = (ImageView)findViewById(R.id.res_book_res_content_upordown);
//		infoImgUporDown = (ImageView)findViewById(R.id.member_info_upordown);
	}
	
	private void bindEvent(){
 
		llback.setOnClickListener(this);
		llexit.setOnClickListener(this);
		bt_editInfo.setOnClickListener(this);
		bt_watchedRes.setOnClickListener(this);
		bt_ordered.setOnClickListener(this);
		bt_trends.setOnClickListener(this);
		bt_chat.setOnClickListener(this);
		bt_cate.setOnClickListener(this);
		btFans.setOnClickListener(this);
		btAttention.setOnClickListener(this);
//		llLabels.setOnClickListener(this);
//		llInfo.setOnClickListener(this);
		btPlan.setOnClickListener(this);
		btHealthShare.setOnClickListener(this);
		imgUser.setOnClickListener(this);
	}
	
	private void initData(){
		user = Global.user;
		if (user!=null) {
			tvUserName.setText(user.getUserName());
			String sex = "-";
			if(!StringUtils.isEmpty(user.getSex())) {
				if (user.getSex().equals("1")) {
					sex = "男";
				}else if(user.getSex().equals("2")) {
					sex = "女";
				}
			}
			
			tvSex.setText(sex);
			tv_heigth.setText(user.getHeight() + " cm");
			tv_weight.setText(user.getWeight() + " Kg");
			tv_checkedBody.setText(user.getCheckedBody());
			tvLabels.setText(user.getLabels());
			tvInfo.setText(user.getInfo());
			System.out.println("合理指数："+user.getLevel());
			rbLevel.setRating(user.getLevel());
			loadHeadIcon(imgUser, user.getImgUrl());
		}
	}
	 private void loadHeadIcon(ImageView iv, String ImgUrl) {
	        Bitmap bitmap = AsyncBitmapLoader.getInstance().loadBitmap(iv, ImgUrl, new ImageCallBack() {  
	            public void imageLoad(ImageView imageView, Bitmap bitmap) { 
	            	if(bitmap == null) {    
	            		imageView.setImageResource(R.drawable.headicon);    
	    			} else {    
	    				imageView.setImageBitmap(bitmap);    
	    			} 
	            }  
	        });  
			if(bitmap == null) {    
				iv.setImageResource(R.drawable.headicon);    
			} else {    
				iv.setImageBitmap(bitmap);    
			}
		}
 
	public void onClick(View v) {
		bt_more.setVisibility(Button.GONE);
		Intent intent = new Intent();
		switch(v.getId()) {

		case R.id.homepage_personal_img:
			intent.putExtra("userId", user.getUserId());
			intent.setClass(ctx, HeadPortraitActivity.class);
			ctx.startActivity(intent);
			ctx.finish();
			break;
		case R.id.res_info_back:
			ctx.finish();
			//ctx.setContentView(new LoginWidget(ctx));
			break;
		case R.id.homepage_personal_info_exit:
			showExitDialog();
			break;
		case R.id.homepage_personal_edit_info_bt:
			ctx.setContentView(new EditUserInfoWidget(ctx));
			break;
		case R.id.homepage_personal_attention_res_bt:
			ctx.setContentView(new HomepageWatchedResWidget(ctx));
			break;
		case R.id.homepage_personal_consumption_bt:
			ctx.setContentView(new HomepageOrderedWidget(ctx));
			break;
		case R.id.homepage_personal_share_bt:
			ctx.setContentView(new HomepageFriendsTrendsWidget(ctx));
			break;
		case R.id.homepage_personal_new_message_bt:
			//ctx.setContentView(new HomepageChatWidget(ctx));
			//ctx.setContentView(new HomepageChatWidget2(ctx));
			intent.setClass(ctx, ChatActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.homepage_personal_cate_bt:
			intent.setClass(ctx, HealthCateActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.homepage_personal_comment_bt:
			intent.setClass(ctx, HealthShareActivity.class);
			intent.putExtra("userName", Global.user.getUserName());
			ctx.startActivity(intent);
			break;
//			if(tvLabels.getVisibility() == View.GONE || tvLabels.getVisibility() == View.INVISIBLE){
//				tvLabels.setVisibility(View.VISIBLE);
//				imgUporDown.setBackgroundResource(R.drawable.close_more);
//			}else {
//				tvLabels.setVisibility(View.GONE);
//				imgUporDown.setBackgroundResource(R.drawable.open_more);
//			}
//			break;
//		case R.id.homepage_member_info_linearlayout:
//			if(tvInfo.getVisibility() == View.GONE || tvInfo.getVisibility() == View.INVISIBLE){
//				tvInfo.setVisibility(View.VISIBLE);
//				infoImgUporDown.setBackgroundResource(R.drawable.close_more);
//			}else {
//				tvInfo.setVisibility(View.GONE);
//				infoImgUporDown.setBackgroundResource(R.drawable.open_more);
//			}
//			break;
		case R.id.homepage_personal_fans_bt:
			Bundle bundle = new Bundle();
			bundle.putSerializable("user", user);
			ctx.getIntent().putExtras(bundle);
			ctx.getIntent().putExtra("type", "1");
			ctx.getIntent().putExtra("FromWidgetFlag", "HomepagePersonalWidget");
			ctx.setContentView(new FansAttentionListWidget(ctx));
			break;
		case R.id.homepage_personal_attention_bt:
			bundle = new Bundle();
			bundle.putSerializable("user", user);
			ctx.getIntent().putExtras(bundle);
			ctx.getIntent().putExtra("type", "2");
			ctx.getIntent().putExtra("FromWidgetFlag", "HomepagePersonalWidget");
			ctx.setContentView(new FansAttentionListWidget(ctx));
			break;
		case R.id.homepage_personal_plan_bt:
			intent = new Intent(ctx,CalendarActivity.class);
			intent.putExtra("userId", user.getUserId());
			ctx.startActivity(intent);
			break;

		case R.id.personal_hide_jkdr_linearlayout:
			myPopupWindow.dismiss();
			intent.setClass(ctx, MemberActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.personal_hide_health2_linearlayout:
			myPopupWindow.dismiss();
			intent.setClass(ctx, HealthMirrorActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.personal_hide_jkcd_linearlayout:
			myPopupWindow.dismiss();
			intent.setClass(ctx, HealthShareActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.personal_hide_diy_linearlayout:
			myPopupWindow.dismiss();
			intent = new Intent(ctx, DIYActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.personal_hide_shejianhot_linearlayout:
			myPopupWindow.dismiss();
			intent.setClass(ctx, CityWideActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.personal_hide_sjjk_linearlayout:
			myPopupWindow.dismiss();
			intent.setClass(ctx, RecommendHealthActivity.class);
			ctx.startActivity(intent);
			break;
		case R.id.personal_hide_share_linearlayout:
			myPopupWindow.dismiss();
			intent = new Intent(ctx, MoreActivity.class);
			intent.putExtra("do", "share");
			ctx.startActivity(intent);
			break;
			
		default:
			break;
		}
	}
	private void showExitDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		builder.setTitle("退出");
		//builder.setIcon(R.drawable.what);
		builder.setMessage("您已选择退出个人后台中心，是否确定退出？");
		builder.setCancelable(false);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				exitPersonCenter();
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}
	private void exitPersonCenter() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userId", Global.user.getUserId()));
					response = HttpUtils.Post(url_exit, params);
					
					if(Global.DEBUG) {
						System.out.println("exitPersonCenter-----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e("loginOut", "Exception", e);
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	@Override
	public void notifyAdapter() {
		
	}
 
}
